import { Injectable } from '@angular/core';
import { InAppBrowser } from '@ionic-native/in-app-browser';
import { FileOpener } from '@ionic-native/file-opener';
import { File } from '@ionic-native/file';
import { Events, App, AlertController, Platform, LoadingController } from 'ionic-angular';
import { Config } from './config';
import { Storage } from '@ionic/storage';
import { HttpClient } from './httpClient';

import _ from 'lodash';
import * as moment from "moment";

@Injectable()
export class Common {
  constructor(public config: Config,
    public storage: Storage,
    public fileOpener: FileOpener,
    public inAppBrowser: InAppBrowser,
    public alertCtrl: AlertController,
    public file: File,
    public app: App,
    public events: Events,
    public platform: Platform,
    public loadingCtrl: LoadingController,
    public httpClient: HttpClient) {
  }


  addWatermark(view) {
    console.log('------------viewWillEnter----------------')
    console.log(view)
    if (view.instance.moa_page_name) {
      this.storage.get("configs").then(configs => {
        console.log('------------configs----------------')
        //console.log(configs);
        if (configs && configs.length > 0) {
          let watermark: any = _.find(configs, {
            name: "watermark"
          })['json'];
          console.log('------------watermark----------------')
          // console.log(watermark);
          this.storage.get("userInfo").then(userInfo => {
            if (_.indexOf(watermark.list, view.instance.moa_page_name) > -1) {
              _.templateSettings.interpolate = /{{([\s\S]+?)}}/g;
              var compiled = _.template(watermark.template);
              let watermark_txt = compiled(userInfo);
              console.log('--该页面需要加水印哦---');
              // console.log(watermark_txt);
              // document.getElementById("watermark-content").innerHTML = "";
              watermark.config.watermark_txt = watermark_txt;
              watermark.config.page_name = view.instance.moa_page_name;
              window['watermark'](watermark.config);
            } else {
              // document.getElementById("watermark-content").innerHTML = "";
            }
          });
        }
      });
    }
  }

  /**
   * 保存用户行为数据
   * @param component
   * @param subOperate
   * @param title
   * @returns {boolean}
   */
  saveUserStatistics(component, subOperate, title) {
    if (!component) {
      return false;
    }
    if (component === "page-login") {
      return false;
    }

    this.storage.get("userInfo").then(user => {
      if (user) {
        let statistics = {
          loginid: user.loginid,
          username: user.emname,
          component: component,
          subOperate: subOperate,
          title: title,
          operateTime: moment().format("YYYY-MM-DD HH:mm:ss:SSS")
        };

        // setTimeout(() => {
        /*this.httpClient.post([statistics], {
          isShowLoading: false,
          url: this.config.server + "api/v1/common/statistics/save"
        }).subscribe(result => {
          console.log("saveUserStatistics>>>>>>>>>>", result);
        });*/
        // }, 2000);

        this.storage.get("UserStatistics").then(UserStatistics => {
          if (!UserStatistics) {
            UserStatistics = [];
          }
          UserStatistics.push(statistics);
          this.storage.set("UserStatistics", UserStatistics);
        });
      }
    });
  }

  /**
   * alert一个信息
   */
  alertMessage(msg) {
    let errorAlert = this.alertCtrl.create({
      title: "提示",
      message: msg,
      buttons: [
        {
          text: "确定",
          role: 'cancel',
          handler: () => {
          }
        }
      ]
    });
    errorAlert.present();
  }

  syncContactList(type, isNotShowLoading?) {
    let that = this;
    var promise = new Promise(function (resolve, reject) {
      if (type == 'local') {
        that.storage.get('contact-user-list').then(listData => {
          that.storage.get('contact-tag-list').then(tagList => {
            resolve({
              listData: listData,
              tagList: tagList
            })
          });
        });
      } else if (type === 'server') {
        let postBody = {
          "module": "OAServer",
          "method": "getContactAllList",
          "params": {}
        };
        let postConfig: any = {
          loadingText: "正在同步最新通讯录,请稍候..."
        }
        if (isNotShowLoading) {
          postConfig.isAlterError = false;
          postConfig.isShowLoading = false;
        }
        that.httpClient.post(postBody, postConfig).subscribe(data => {
          if (data) {
            resolve({
              listData: data.userList,
              tagList: data.tagList
            })
            that.storage.set('contact-user-list', data.userList);
            that.storage.set('contact-org-list', data.orgList);
            that.storage.set('contact-tag-list', data.tagList);
            that.storage.set('contact-last-sync-time', new Date().getTime());
          }
        });
      }
    });
    return promise;
  }

  /**
   * [checkUrl 检查URL是否可以打开或者跳转]
   * @param {[type]} url [description]
   */
  checkUrl(url) {
    let that = this;
    let postBody = {
      "module": "OAServer",
      "method": "checkUrl",
      "params": {
        "url": url
      }
    };
    that.httpClient.post(postBody).subscribe(result => {
      console.info(result);
      if (result) {
        if (result.isOpen) {
          if (result.type == 'webview') {
            that.openInAppBrowser(url);
            console.info(url)
          } else if (result.type == 'app') {
            // console.info(that.app.getRootNav().push(InfoDetailPage));
            that.events.publish('html-open-link:app', result);
          }
        } else {
          let alert = that.alertCtrl.create({
            title: '提示',
            subTitle: result.msg,
            buttons: ['OK']
          });
          alert.present();
        }
      }
    });

  };


  /**
   * [bindLinkersEvent 给特定容器的a标签绑定跳转事件]
   * @param {[type]} selector [description]
   */
  bindLinkersEvent(selector) {
    let that = this;
    setTimeout(function () {
      let contents = document.getElementsByTagName(selector)[0].getElementsByClassName("html-content");
      _.each(contents, function (content, i) {
        let linkers = content.getElementsByTagName("a");
        _.each(linkers, function (link, index) {
          console.info('--------bind link-------');
          console.info(link);
          link.addEventListener("click", function (event) {
            let _that = this;
            event.preventDefault();
            console.info('---------click a tag-----------');
            console.info(link.href);
            // if (_.startsWith(link.href, 'file:/')) {
            if (_.endsWith(link.href, '#')) {
              // 如果是hash结尾，不处理跳转
            } else {
              if (selector === "page-bcw-home-detail") {
                let url = _that['href'];
                url = _.replace(url, "http://10.88.102.172/", that.config.server + "bcwpdf/");
                url += "?isBCWPDF=true";
                that.checkUrl(url);
              } else {
                that.checkUrl(_that['href']);
              }
            }
            return false;
          });
        });
      })
    }, 100);
  }

  /**
   * [tranformImgLik 通过正则匹配图片的src并且替换]
   * @param {[type]} str [description]
   */
  tranformImgLik(str, isNormal) {
    let that = this;
    var promise = new Promise(function (resolve, reject) {
      that.storage.get('id_token').then((token) => {
        //匹配图片（g表示匹配所有结果i表示区分大小写）
        var imgReg = /<img.*?(?:>|\/>)/gi;
        var srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i;
        str = str.replace(new RegExp(imgReg), function (img) {
          console.info('----------------------------');
          img = img.replace(new RegExp(srcReg), function (src) {
            var url = src.replace('src=', '');
            var replaceUrl = 'src="' + that.config.server + "api/v1/common/img?access_token=" + token + "&url=";
            console.info(replaceUrl);
            console.info(src + '');
            if (isNormal) {
              if (src.indexOf("data:image") > -1) {
                src = src;
              } else if (src.indexOf(replaceUrl) < 0) {
                src = src.replace(/src="/i, replaceUrl);
              }
            } else {
              src = _.replace(src, '&amp;', '&');
              src = _.replace(src, replaceUrl, 'src="');
            }
            console.info(src);
            return src;
          });
          return img;
        });
        resolve(str);
      });
    });
    return promise;
  }


  /**
   * [formatListData 格式化提交数据]
   * @param {[type]} list [description]
   */
  formatContactListData(list) {
    let r = "";
    _.each(list, function (item, index) {
      // 如果是个人
      if (item.empid) {
        r = r + ",CN=" + item.empid + "/TI=" + item.titleid + "/OU=" + item.orgid;
        // 如果是岗位
      } else if (item.titleid) {
        r = r + ",TI=" + item.titleid + "/OU=" + item.orgid;
        // 如果是组织
      } else {
        r = r + ",OU=" + item.orgid;
      }
    });
    r = r.substr(1);
    return r;
  };

  /**
   * [getExtension 获取文件名后缀]
   * @param {[type]} filename [description]
   */
  getExtension(filename) {
    var index = _.lastIndexOf(filename, '.');
    console.info(filename);
    return filename.substring(index + 1, filename.length);
  }


  getVersionInfo() {
    let promise = new Promise(function (resolve, reject) {
      let version: any = {};
      if (window['chcp']) {
        window['chcp'].getVersionInfo(function (err, version) {
          version.appVersion = version.appVersion;
          version.h5Version = version.currentWebVersion;
          resolve(version);
        });
      } else {
        version.appVersion = '3.0.0';
        version.h5Version = "2017.04.27-18.08.08";
        resolve(version);
      }
    });
    return promise;
  }

  openInAppBrowser(link) {
    let browser = this.inAppBrowser.create(link, '_blank', 'location=no,closebuttoncaption=关闭,enableViewportScale=yes,toolbarposition=top,zoom=yes,clearcache=yes,clearsessioncache=yes');
  };

  /**
   * [openFile 使用webview打开文件]
   * @param {[type]} type [description]
   * @param {[type]} id   [description]
   */
  openFile(type, format, id, name, isRemote, isNotStore?) {
    console.info('----- common openFile-----');
    if (format !== 'pdf') {
      format = 'normal';
    }
    if (!isNotStore) {
      this.storage.get('open_file_history').then((fileList) => {
        fileList = fileList ? fileList : [];
        // 移除之前看过的记录，添加新记录
        _.remove(fileList, { id: id });
        if (fileList.length >= 20) {
          var last = fileList[0];
          _.remove(fileList, { id: last.id });
        }
        fileList.push({
          id: id,
          name: name,
          type: type,
          format: format
        });
        this.storage.set('open_file_history', fileList);
      });
    }
    let fileExt = this.getExtension(name);

    this.storage.get('id_token').then(token => {
      console.info(token);
      if (token) {
        let link = this.config.server + 'api/v1/common/attach/' + type + "/" + format + "/" + isRemote + "/" + id + "." + fileExt + "?access_token=" + token;
        console.info(link);
        if (this.platform.is("ios")) {
          if (_.indexOf(this.config.ios_file_black_list, fileExt) > -1) {
            let alert = this.alertCtrl.create({
              title: '提示',
              subTitle: '该附件类型不支持在手机OA打开',
              buttons: ['OK']
            });
            alert.present();
          } else {
            this.openInAppBrowser(link);
          }
        } else {
          if (this.platform.is('cordova')) {
            this._openCheckFile(link, name);
          } else {
            this.openInAppBrowser(link);
          }
        }
      }
    });
  }

  // 删除本地存储的文件
  removeDownloadAttach(isNotShowAlert?) {
    this.storage.set('open_file_history', []);
    if (this.platform.is("android") && this.platform.is('cordova')) {
      this.file.removeRecursively(window['cordova'].file.externalDataDirectory, "attach").then((result) => {
        console.info(result);
      }).catch((err) => {
        console.info(err);
      });
    }
    if (!isNotShowAlert) {
      let alert = this.alertCtrl.create({
        title: '提示',
        subTitle: '清理缓存成功',
        buttons: ['OK']
      });
      alert.present();
    }
  }

  _openCheckFile(link, name) {
    let that = this;
    this.httpClient.post({}, {
      url: link
      // isAuthHttp: false
    }).subscribe(fileData => {
      console.info(fileData);
      if (fileData) {
        this.file.checkFile(window['cordova'].file.externalDataDirectory + "/attach/", fileData.filename).then((isExit) => {
          console.info('----------checkFile---------')
          console.info(isExit)
          if (isExit) {
            var storeFile = window['cordova'].file.externalDataDirectory + 'attach/' + fileData.filename;
            that._openAndroidFile(storeFile, fileData);
          } else {
            that._askIsDownload(link, fileData);
          }
        }).catch(err => {
          console.info('----------checkFile  err---------')
          console.info(err)
          fileData.name = name;
          that._askIsDownload(link, fileData);
        });
      }
    });
  }

  _askIsDownload(link, fileData) {
    let fileSize: any = fileData.size / 1024;
    if (fileSize > 1024) {
      fileSize = (fileSize / 1024).toFixed(2) + "MB";
    } else {
      fileSize = fileSize.toFixed(2) + "KB";
    }
    let that = this;
    let alert = that.alertCtrl.create({
      title: '提示',
      message: '文件名：' + fileData.name + '<br/>文件大小：' + fileSize + '<br/>是否确认下载该文件?',
      buttons: [
        {
          text: '取消',
          role: 'cancel',
          handler: data => {
            console.log('Cancel clicked');
          }
        },
        {
          text: '确认',
          handler: data => {
            that._downloadFile(link, fileData);
          }
        }
      ]
    });
    alert.present();
  }

  _openAndroidFile(storeFile, fileData) {
    let that = this;
    this.fileOpener.open(storeFile, fileData.mime).then(() => {
      console.info('opensuccess');
    }).catch((err) => {
      let alert = that.alertCtrl.create({
        title: '提示',
        subTitle: '文件下载成功，系统检测到无对应软件能打开该类型的附件',
        buttons: ['OK']
      });
      alert.present();
      console.info(err);
    });
  }

  _downloadFile(link, fileData) {
    let that = this;
    let fileTransfer = new window['FileTransfer']();
    fileTransfer.onprogress = function (progressEvent) {
      console.info('------------_downloadFile onprogress-------------------');
      if (progressEvent.lengthComputable) {
        var p = ((progressEvent.loaded / progressEvent.total) * 100).toFixed(2) + "%";
        document.getElementsByClassName("gfoa-download-percentage")[0].innerHTML = p;
      }
    };
    let alert1 = this.alertCtrl.create({
      title: '提示',
      message: '正在下载文件,请稍候...<br/>已完成：<span class="gfoa-download-percentage">0%</span>',
      enableBackdropDismiss: false,
      buttons: [{
        text: '取消下载',
        handler: () => {
          fileTransfer.abort();
        }
      }]
    });
    alert1.present();
    // let loader1 = this.loadingCtrl.create({
    // 	content: "正在下载文件,请稍候..."
    // });
    // loader1.present();
    var uri = encodeURI(link);
    var storeFile = window['cordova'].file.externalDataDirectory + '/attach/' + fileData.filename;
    fileTransfer.download(
      uri,
      storeFile,
      function (entry) {
        alert1.dismiss();
        that._openAndroidFile(storeFile, fileData);
      },
      function (error) {
        alert1.dismiss();
        let alert = that.alertCtrl.create({
          title: '提示',
          subTitle: '文件下载失败,请稍候重试！',
          buttons: ['好的']
        });
        alert.present();
      },
      false,
      {
        headers: {}
      }
    );
  }

  /**
   * [updateApp 更新原生应用]
   * @param {[type]} data [description]
   */
  updateApp(data) {
    let browser = this.inAppBrowser.create(data.downloadUrl, '_system');
  }

  /**
   * [updateHtml5 更新H5页面]
   * @param {[type]} data [description]
   */
  updateHtml5(data) {
    let _that = this;
    let loader1 = this.loadingCtrl.create({
      content: "正在更新文件,请稍候..."
    });
    loader1.present();
    var options = {
      'config-file': data.downloadUrl,
      'request-headers': {}
    };
    window['chcp'].fetchUpdate(function updateCallback(error, data) {
      loader1.dismiss();
      console.info(error);
      console.info(data);
      if (!error) {
        let loader2 = _that.loadingCtrl.create({
          content: "正在替换文件,请稍候..."
        });
        loader2.present();
        window['chcp'].installUpdate(function (error) {
          loader2.dismiss();
          let tips = ''
          if (!error) {
            tips = '更新成功!应用即将重新加载!';
          } else {
            tips = '重新加载异常,请稍候重试!';
          }
          console.info(tips);
          let alert = _that.alertCtrl.create({
            title: '提示',
            subTitle: tips,
            buttons: ['确认'],
            enableBackdropDismiss: false
          });
          alert.present();
        });
      } else {
        let alert = _that.alertCtrl.create({
          title: '提示',
          subTitle: '更新文件异常,请稍候重试!',
          enableBackdropDismiss: false,
          buttons: ['确认']
        });
        alert.present();
      }
    }, options);
  }


  /**
   * [checkUpdateData 远程调用检查最新版本]
   * @param {[type]} appVersion [description]
   * @param {[type]} h5Version  [description]
   * @param {[type]} type       [description]
   */
  checkUpdateData(appVersion, h5Version, type, options, userInfo) {
    let postBody = {
      "appVersion": appVersion,
      "h5Version": h5Version,
      "type": type,
      "username": userInfo ? userInfo.loginid : ""
    };
    var option = {
      url: this.config.server + "api/v1/versions/check",
      isAuthHttp: false
    };
    return this.httpClient.post(postBody, _.assignIn(option, options));
  }

  /**
   * [checkUpdate 检查更新方法]
   */
  checkUpdate(options) {
    console.info('------------checkUpdate-----------');
    let _that = this;
    let type = '';
    if (this.platform.is('ios')) {
      type = 'ios';
    } else {
      type = 'android';
    }
    // if (this.platform.is('cordova')) {
    this.getVersionInfo().then((version: any) => {
      //读取当前用户token
      this.storage.get('userInfo').then((userInfo) => {
        _that.checkUpdateData(version.appVersion, version.h5Version, type, options, userInfo).subscribe(data => {
          if (data) {
            if (data.hasOwnProperty("id")) {
              _that.storage.set('newVersionInfo', data);
              let buttons = [];
              if (data.updateType == 'normal') {
                buttons.push({
                  text: '取消',
                  handler: () => {
                    console.log('取消更新');
                  }
                });
              }

              buttons.push({
                text: '更新',
                handler: () => {
                  if (data.type == 'html5') {
                    _that.updateHtml5(data);
                  } else {
                    _that.updateApp(data);
                  }
                  console.log('操作更新');
                  // 如果是紧急更新，则一定要更新后才隐藏遮罩层
                  if (data.updateType !== 'normal') {
                    return false;
                  }
                }
              });

              // 检测，是否之前有登录过用户
              // _that.storage.get('userInfo').then((userInfo) => {
              // 	if (userInfo) {

              // 	} else {

              // 	}
              // });

              let confirm = _that.alertCtrl.create({
                title: '发现新版本',
                message: data.changeLog,
                cssClass: "update_alert",
                enableBackdropDismiss: false,
                buttons: buttons
              });
              confirm.present();
            } else {
              if (options.isAlterTips) {
                let alert = _that.alertCtrl.create({
                  title: '提示',
                  subTitle: '已经是最新版本!',
                  enableBackdropDismiss: false,
                  buttons: ['确认']
                });
                alert.present();
              }
            }
          }
        });
      });
    });

    // } else {
    // 	let alert = this.alertCtrl.create({
    // 		title: '提示',
    // 		subTitle: '请在App里面使用更新功能!',
    // 		enableBackdropDismiss: false,
    // 		buttons: ['确认']
    // 	});
    // 	alert.present();
    // }
  }

  /**
   * 根据简拼获取姓名
   * @param keyWord 输入的简拼字符
   * @param mode  模式：0表示只按照简拼查询，1表示只按照部门查询，2表示按照简拼以及部门双查询
   */
  getContactNameByJianPin(keyWord, mode) {
    keyWord = keyWord.toLowerCase();
    let that = this;
    let promise = new Promise(function (resolve, reject) {
      let dataList = [];
      that.storage.get('contact-user-list').then(data => {
        _.each(data, function (item, i) {
          switch (mode) {
            case 0:
              if (item.full_pinyin.indexOf(keyWord) > -1) {
                dataList.push(item.emname);
              } else {
                if (item.emname.indexOf(keyWord) > -1) {
                  dataList.push(item.emname);
                }
              }
              break;
            case 1:
              _.each(item.full_orgnames, function (orgname, ii) {
                if (orgname.pinyin && orgname.pinyin.indexOf(keyWord) > -1) {
                  dataList.push(item.emname);
                }
              });
              break;
            case 2:
              if (item.full_pinyin.indexOf(keyWord) > -1) {
                dataList.push(item.emname);
              } else {
                _.each(item.full_orgnames, function (orgname, ii) {
                  if (orgname.pinyin && orgname.pinyin.indexOf(keyWord) > -1) {
                    dataList.push(item.emname);
                  }
                });
              }
              break;
          }
          /*if (i == data.length - 1) {
           resolve(dataList);
           }*/
        });
        resolve(dataList);
      });

    });
    return promise;
  }

  /**
   * [getNowFormatDate 获取当前时间]
   * 返回格式：YYYY-MM-DD
   */
  getNowFormatDate() {
    var retVal = "";
    var date = new Date();
    var seperator1 = "-";
    var year = date.getFullYear();
    retVal = _.toString(year);
    var m = date.getMonth() + 1;
    var strDate = date.getDate();
    if (m >= 1 && m <= 9) {
      retVal += (seperator1 + "0" + m);
    } else {
      retVal += (seperator1 + m);
    }

    if (strDate >= 0 && strDate <= 9) {
      retVal += (seperator1 + "0" + strDate);
    } else {
      retVal += (seperator1 + strDate);
    }
    return retVal;
  }

  /**
   * [getDate 当前日期追加多少天]
   * @param {[type]} stamp [天数]
   * 返回格式：YYYY-MM-DD
   */
  getDate(stamp) {
    var retVal = "";
    var date = new Date();
    date.setDate(date.getDate() + stamp); // 当前时间追加多少天
    var seperator1 = "-";
    var year = date.getFullYear();
    retVal = _.toString(year);
    var m = date.getMonth() + 1;
    var strDate = date.getDate();
    if (m >= 1 && m <= 9) {
      retVal += (seperator1 + "0" + m);
    } else {
      retVal += (seperator1 + m);
    }


    if (strDate >= 0 && strDate <= 9) {
      retVal += (seperator1 + "0" + strDate);
    } else {
      retVal += (seperator1 + strDate);
    }
    return retVal;
  }

  dealDate(targetDate, stamp) {
    var retVal = "";
    var date = new Date(_.replace(targetDate, /-/g, "/"));
    date.setDate(date.getDate() + stamp); // 当前时间追加多少天
    var seperator1 = "-";
    var year = date.getFullYear();
    retVal = _.toString(year);
    var m = date.getMonth() + 1;
    var strDate = date.getDate();
    if (m >= 1 && m <= 9) {
      retVal += (seperator1 + "0" + m);
    } else {
      retVal += (seperator1 + m);
    }


    if (strDate >= 0 && strDate <= 9) {
      retVal += (seperator1 + "0" + strDate);
    } else {
      retVal += (seperator1 + strDate);
    }
    return retVal;
  }

  /**
   * [getLastDay 获取当前时间的前一天]
   * 返回格式： YYYY-MM-DD
   */
  getLastDay() {
    return this.getDate(-1);
  }

  /**
   * 获取上一个月同一天日期
   * @param date 当前日期，日期格式必须为：yyyy-MM-dd
   */
  getPreMonth(date) {
    var arr = date.split('-');
    var year = arr[0]; //获取当前日期的年份
    var month = arr[1]; //获取当前日期的月份
    var day = arr[2]; //获取当前日期的日
    var days = new Date(year, month, 0);
    let ds = days.getDate(); //获取当前日期中月的天数
    var year2 = year;
    var month2 = parseInt(month) - 1;
    if (month2 == 0) {
      year2 = parseInt(year2) - 1;
      month2 = 12;
    }
    var day2 = day;
    var days2 = new Date(year2, month2, 0);
    let ds2 = days2.getDate();
    if (day2 > ds2) {
      day2 = ds2;
    }
    let temp_month2 = null;
    if (month2 < 10) {
      temp_month2 = _.toString(month2);
      temp_month2 = '0' + temp_month2;
    } else {
      temp_month2 = month2;
    }
    var t2 = year2 + '-' + temp_month2 + '-' + day2;
    return t2;
  }


  /**
   * [getDate 当前日期追加多少天]
   * @param {[type]} stamp [天数]
   * 返回格式：YYYY-MM-DD hh:mm:ss
   */
  getTime(stamp) {
    var retVal = "";
    var date = new Date();
    date.setDate(date.getDate() + stamp); // 当前时间追加多少天
    var seperator1 = "-";
    var year = date.getFullYear();
    retVal = _.toString(year);
    var m = date.getMonth() + 1;
    var strDate = date.getDate();

    var h = date.getHours();
    var mi = date.getMinutes();
    var s = date.getSeconds();

    // 月
    if (m >= 1 && m <= 9) {
      retVal += (seperator1 + "0" + m);
    } else {
      retVal += (seperator1 + m);
    }

    // 日
    if (strDate >= 0 && strDate <= 9) {
      retVal += (seperator1 + "0" + strDate);
    } else {
      retVal += (seperator1 + strDate);
    }
    // 时
    if (h >= 0 && h <= 9) {
      retVal += (" " + "0" + h);
    } else {
      retVal += (" " + h);
    }

    // 分
    if (mi >= 0 && mi <= 9) {
      retVal += (":" + "0" + mi);
    } else {
      retVal += (":" + mi);
    }

    // 秒
    if (s >= 0 && s <= 9) {
      retVal += (":" + "0" + s);
    } else {
      retVal += (":" + s);
    }


    return retVal;
  }

  /**
   * [getT 获取当前时间]
   */
  getT() {
    var retVal = "";
    var date = new Date();

    var h = date.getHours();
    var mi = date.getMinutes();
    var s = date.getSeconds();

    // 时
    if (h >= 0 && h <= 9) {
      retVal += ("0" + h);
    } else {
      retVal += h;
    }

    // 分
    if (mi >= 0 && mi <= 9) {
      retVal += (":" + "0" + mi);
    } else {
      retVal += (":" + mi);
    }

    // 秒
    if (s >= 0 && s <= 9) {
      retVal += (":" + "0" + s);
    } else {
      retVal += (":" + s);
    }

    return retVal;
  }

  // 用于XML指定参数类型
  attributes = {
    "xsi:type": "xs:string",
    "xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
    "xmlns:xs": "http://www.w3.org/2001/XMLSchema"
  }

  formatNumberToAccountancy(target) {
    let result = "";
    if (target) {
      let fix = "";
      if (target.indexOf("-") > -1) {
        fix = "-";
        target = _.replace(target, "-", "");
      }
      let temp = target.split(".");
      if (temp[0]) {
        let length = temp[0].length;
        let remainder = length % 3;
        let mark = remainder == 0 ? remainder : remainder - 1;
        for (var i = length - 3; i > mark; i -= 3) {
          result = "," + temp[0].substr(i, 3) + result;
        }
        result = fix + temp[0].substr(0, remainder == 0 ? 3 : remainder) + result;
        if (temp[1]) {
          result = result + "." + temp[1].substr(0, 2);
          if (temp[1].length == 1) {
            result = result + "." + temp[1] + "0";
          }
        } else {
          // result = result + ".00";
        }
      }
    }
    return result;
  }

  formatNumberToAccountancy2(target, fixed) {
    let result = "";
    if (target) {
      if (fixed) {
        fixed = 2;
      }

      let temp_target = _.toString(target).split(".");
      if (temp_target[1]) {
        if (temp_target[1].length <= 2) {
          fixed = 2;
        }
      } else {
        fixed = 2;
      }

      target = _.toString(parseFloat(target).toFixed(fixed));
      let fix = "";
      if (target.indexOf("-") > -1) {
        fix = "-";
        target = _.replace(target, "-", "");
      }
      let temp = target.split(".");
      if (temp[0]) {
        let length = temp[0].length;
        let remainder = length % 3;
        let mark = remainder == 0 ? remainder : remainder - 1;
        for (var i = length - 3; i > mark; i -= 3) {
          result = "," + temp[0].substr(i, 3) + result;
        }
        result = fix + temp[0].substr(0, remainder == 0 ? 3 : remainder) + result;
        if (temp[1]) {
          result = result + "." + temp[1].substr(0, fixed);
          if (temp[1].length == 1) {
            result = result + "." + temp[1] + "0";
          }
        } else {
          if (fixed != 0) {
            result = result + ".00";
          }
        }
      }
    } else {
      result = "0.00";
    }
    return result;
  }

  // 获取手机端类型
  getClientType() {
    var retVal = "其他客户端";
    if (this.platform.is("android")) {
      retVal = "Android";
    } else if (this.platform.is("iphone")) {
      retVal = "iPhone";
    } else if (this.platform.is("ipad")) {
      retVal = "iPad";
    }

    return retVal;
  }

  numToWeek(num, type) {
    let week = "";
    switch (num) {
      case 1:
        switch (type) {
          case 0:
            week = "周一";
            break;
          case 1:
            week = "星期一";
            break;
        }
        break;
      case 2:
        switch (type) {
          case 0:
            week = "周二";
            break;
          case 1:
            week = "星期二";
            break;
        }
        break;
      case 3:
        switch (type) {
          case 0:
            week = "周三";
            break;
          case 1:
            week = "星期三";
            break;
        }
        break;
      case 4:
        switch (type) {
          case 0:
            week = "周四";
            break;
          case 1:
            week = "星期四";
            break;
        }
        break;
      case 5:
        switch (type) {
          case 0:
            week = "周五";
            break;
          case 1:
            week = "星期五";
            break;
        }
        break;
      case 6:
        switch (type) {
          case 0:
            week = "周六";
            break;
          case 1:
            week = "星期六";
            break;
        }
        break;
      case 7:
        switch (type) {
          case 0:
            week = "周日";
            break;
          case 1:
            week = "星期日";
            break;
        }
        break;
    }
    return week;
  }

  /**
   * 获取触摸方向
   */
  GetSlideDirection(startX, startY, endX, endY) {
    var dy = startY - endY;
    var dx = endX - startX;
    var result = 0;

    //如果滑动距离太短
    if (Math.abs(dx) < 2 && Math.abs(dy) < 2) {
      return result;
    }

    var angle = this.GetSlideAngle(dx, dy);
    if (angle >= -45 && angle < 45) {
      result = 4;
    } else if (angle >= 45 && angle < 135) {
      result = 1;
    } else if (angle >= -135 && angle < -45) {
      result = 2;
    } else if ((angle >= 135 && angle <= 180) || (angle >= -180 && angle < -135)) {
      result = 3;
    }

    return result;
  }

  /**
   * 计算触摸角度
   */
  GetSlideAngle(dx, dy) {
    return Math.atan2(dy, dx) * 180 / Math.PI;
  }

  changeMoneyToChinese(money) {
    var cnNums = new Array("零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"); //汉字的数字
    var cnIntRadice = new Array("", "拾", "佰", "仟"); //基本单位
    var cnIntUnits = new Array("", "万", "亿", "兆"); //对应整数部分扩展单位
    var cnDecUnits = new Array("角", "分", "毫", "厘"); //对应小数部分单位
    //var cnInteger = "整"; //整数金额时后面跟的字符
    var cnIntLast = "元"; //整型完以后的单位
    var maxNum = 999999999999999.9999; //最大处理的数字

    var IntegerNum; //金额整数部分
    var DecimalNum; //金额小数部分
    var ChineseStr = ""; //输出的中文金额字符串
    var parts; //分离金额后用的数组，预定义
    if (money == "") {
      return "";
    }
    money = parseFloat(money);
    if (money >= maxNum) {
      return "";
    }
    if (money == 0) {
      //ChineseStr = cnNums[0]+cnIntLast+cnInteger;
      ChineseStr = cnNums[0] + cnIntLast;
      //document.getElementById("show").value=ChineseStr;
      return ChineseStr;
    }
    money = money.toString(); //转换为字符串
    if (money.indexOf(".") == -1) {
      IntegerNum = money;
      DecimalNum = '';
    } else {
      parts = money.split(".");
      IntegerNum = parts[0];
      DecimalNum = parts[1].substr(0, 4);
    }
    if (parseInt(IntegerNum, 10) > 0) {//获取整型部分转换
      let zeroCount = 0;
      let IntLen = IntegerNum.length;
      for (let i = 0; i < IntLen; i++) {
        let n = IntegerNum.substr(i, 1);
        let p = IntLen - i - 1;
        let q = p / 4;
        let m = p % 4;
        if (n == "0") {
          zeroCount++;
        } else {
          if (zeroCount > 0) {
            ChineseStr += cnNums[0];
          }
          zeroCount = 0; //归零
          ChineseStr += cnNums[parseInt(n)] + cnIntRadice[m];
        }
        if (m == 0 && zeroCount < 4) {
          ChineseStr += cnIntUnits[q];
        }
      }
      ChineseStr += cnIntLast;
      //整型部分处理完毕
    }
    if (DecimalNum != '') {//小数部分
      let decLen = DecimalNum.length;
      for (let i = 0; i < decLen; i++) {
        let n = DecimalNum.substr(i, 1);
        if (n != '0') {
          ChineseStr += cnNums[Number(n)] + cnDecUnits[i];
        }
      }
    }
    if (ChineseStr == '') {
      //ChineseStr += cnNums[0]+cnIntLast+cnInteger;
      ChineseStr += cnNums[0] + cnIntLast;
    }/* else if( DecimalNum == '' ){
     ChineseStr += cnInteger;
     ChineseStr += cnInteger;
     } */
    return ChineseStr;
  }

  ProvinceCityData = [{
    name: "北京",
    cities: ["西城", "东城", "崇文", "宣武", "朝阳", "海淀", "丰台", "石景山", "门头沟", "房山", "通州", "顺义", "大兴", "昌平", "平谷", "怀柔", "密云", "延庆"]
  },
  {
    name: "天津",
    cities: ["青羊", "河东", "河西", "南开", "河北", "红桥", "塘沽", "汉沽", "大港", "东丽", "西青", "北辰", "津南", "武清", "宝坻", "静海", "宁河", "蓟县", "开发区"]
  },
  { name: "河北", cities: ["石家庄", "秦皇岛", "廊坊", "保定", "邯郸", "唐山", "邢台", "衡水", "张家口", "承德", "沧州", "衡水"] },
  { name: "山西", cities: ["太原", "大同", "长治", "晋中", "阳泉", "朔州", "运城", "临汾"] },
  { name: "内蒙古", cities: ["呼和浩特", "赤峰", "通辽", "锡林郭勒", "兴安"] },
  { name: "辽宁", cities: ["大连", "沈阳", "鞍山", "抚顺", "营口", "锦州", "丹东", "朝阳", "辽阳", "阜新", "铁岭", "盘锦", "本溪", "葫芦岛"] },
  { name: "吉林", cities: ["长春", "吉林", "四平", "辽源", "通化", "延吉", "白城", "辽源", "松原", "临江", "珲春"] },
  { name: "黑龙江", cities: ["哈尔滨", "齐齐哈尔", "大庆", "牡丹江", "鹤岗", "佳木斯", "绥化"] },
  {
    name: "上海",
    cities: ["浦东", "杨浦", "徐汇", "静安", "卢湾", "黄浦", "普陀", "闸北", "虹口", "长宁", "宝山", "闵行", "嘉定", "金山", "松江", "青浦", "崇明", "奉贤", "南汇"]
  },
  {
    name: "江苏",
    cities: ["南京", "苏州", "无锡", "常州", "扬州", "徐州", "南通", "镇江", "泰州", "淮安", "连云港", "宿迁", "盐城", "淮阴", "沐阳", "张家港"]
  },
  { name: "浙江", cities: ["杭州", "金华", "宁波", "温州", "嘉兴", "绍兴", "丽水", "湖州", "台州", "舟山", "衢州"] },
  { name: "安徽", cities: ["合肥", "马鞍山", "蚌埠", "黄山", "芜湖", "淮南", "铜陵", "阜阳", "宣城", "安庆"] },
  { name: "福建", cities: ["福州", "厦门", "泉州", "漳州", "南平", "龙岩", "莆田", "三明", "宁德"] },
  { name: "江西", cities: ["南昌", "景德镇", "上饶", "萍乡", "九江", "吉安", "宜春", "鹰潭", "新余", "赣州"] },
  { name: "山东", cities: ["青岛", "济南", "淄博", "烟台", "泰安", "临沂", "日照", "德州", "威海", "东营", "荷泽", "济宁", "潍坊", "枣庄", "聊城"] },
  { name: "河南", cities: ["郑州", "洛阳", "开封", "平顶山", "濮阳", "安阳", "许昌", "南阳", "信阳", "周口", "新乡", "焦作", "三门峡", "商丘"] },
  { name: "湖北", cities: ["武汉", "襄樊", "孝感", "十堰", "荆州", "黄石", "宜昌", "黄冈", "恩施", "鄂州", "江汉", "随枣", "荆沙", "咸宁"] },
  { name: "湖南", cities: ["长沙", "湘潭", "岳阳", "株洲", "怀化", "永州", "益阳", "张家界", "常德", "衡阳", "湘西", "邵阳", "娄底", "郴州"] },
  {
    name: "广东",
    cities: ["广州", "深圳", "东莞", "佛山", "珠海", "汕头", "韶关", "江门", "梅州", "揭阳", "中山", "河源", "惠州", "茂名", "湛江", "阳江", "潮州", "云浮", "汕尾", "潮阳", "肇庆", "顺德", "清远"]
  },
  { name: "广西", cities: ["南宁", "桂林", "柳州", "梧州", "来宾", "贵港", "玉林", "贺州"] },
  { name: "海南", cities: ["海口", "三亚"] },
  { name: "重庆", cities: ["渝中", "大渡口", "江北", "沙坪坝", "九龙坡", "南岸", "北碚", "万盛", "双桥", "渝北", "巴南", "万州", "涪陵", "黔江", "长寿"] },
  { name: "四川", cities: ["成都", "达州", "南充", "乐山", "绵阳", "德阳", "内江", "遂宁", "宜宾", "巴中", "自贡", "康定", "攀枝花"] },
  { name: "贵州", cities: ["贵阳", "遵义", "安顺", "黔西南", "都匀"] },
  { name: "云南", cities: ["昆明", "丽江", "昭通", "玉溪", "临沧", "文山", "红河", "楚雄", "大理"] },
  { name: "西藏", cities: ["拉萨", "林芝", "日喀则", "昌都"] },
  { name: "陕西", cities: ["西安", "咸阳", "延安", "汉中", "榆林", "商南", "略阳", "宜君", "麟游", "白河"] },
  { name: "甘肃", cities: ["兰州", "金昌", "天水", "武威", "张掖", "平凉", "酒泉"] },
  { name: "青海", cities: ["黄南", "海南", "西宁", "海东", "海西", "海北", "果洛", "玉树"] },
  { name: "宁夏", cities: ["银川", "吴忠"] },
  { name: "新疆", cities: ["乌鲁木齐", "哈密", "喀什", "巴音郭楞", "昌吉", "伊犁", "阿勒泰", "克拉玛依", "博尔塔拉"] },
  {
    name: "香港",
    cities: ["中西区", "湾仔区", "东区", "南区", "九龙-油尖旺区", "九龙-深水埗区", "九龙-九龙城区", "九龙-黄大仙区", "九龙-观塘区", "新界-北区", "新界-大埔区", "新界-沙田区", "新界-西贡区", "新界-荃湾区", "新界-屯门区", "新界-元朗区", "新界-葵青区", "新界-离岛区"]
  },
  { name: "澳门", cities: ["花地玛堂区", "圣安多尼堂区", "大堂区", "望德堂区", "风顺堂区", "嘉模堂区", "圣方济各堂区", "路氹城"] }];

}
